package com.leeoohoo.error;

import com.leeoohoo.base.Result;
import com.oohoo.spacestationspringbootstarter.dto.query.exception.DtoQueryException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.bind.support.WebExchangeBindException;
import org.springframework.web.server.ResponseStatusException;
import reactor.core.publisher.Mono;

import java.util.List;


@RestControllerAdvice
@Slf4j
public class CustomExceptionHandler {
    @ExceptionHandler(WebExchangeBindException.class)
    @ResponseStatus(code = HttpStatus.BAD_REQUEST)
    public Mono<Result> webExchangeBindException(WebExchangeBindException e) {
        e.printStackTrace();
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        StringBuilder stringBuilder = new StringBuilder();
        allErrors.forEach(it -> {
            stringBuilder.append(it.getDefaultMessage()).append(";");
        });
        return Mono.just(Result.fail(stringBuilder));
    }

    @ExceptionHandler(ResponseStatusException.class)
    @ResponseStatus(code = HttpStatus.NOT_FOUND)
    public Mono<Result> dtoQueryException(ResponseStatusException e) {
        e.printStackTrace();
        return Mono.just(Result.fail(e.getMessage()));
    }

    @ExceptionHandler(DtoQueryException.class)
    @ResponseStatus(code = HttpStatus.BAD_REQUEST)
    public Mono<Result> dtoQueryException(DtoQueryException e) {
        e.printStackTrace();
        return Mono.just(Result.fail(e.getMessage()));
    }

    @ExceptionHandler(Exception.class)
    @ResponseStatus(code = HttpStatus.INTERNAL_SERVER_ERROR)
    public Mono<Result> handleCustomException(Exception e) {
        e.printStackTrace();
        log.error(e.getMessage());
        return Mono.just(Result.fail("系统发生异常"));
    }


}
